<template>
  <div>
    <h3>修改商品</h3>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="javascript:;">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 警告框 -->
      <el-alert
        title="修改商品信息"
        center
        show-icon
        :closable='false'
        type="info"
      >
      </el-alert>
      <!-- 步骤条、 -->
      <el-steps
        :active="currentIndex-0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品重量"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <!-- 表单嵌套 -->
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          style="height: ;"
          v-model="currentIndex"
          :before-leave='beforeTabLeave'
          @tab-click='tabClicked'
        >
          <el-tab-pane
            label="基本信息"
            name="0"
          >
            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input
                v-model="editForm.goods_price"
                type='number'
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input
                v-model="editForm.goods_weight"
                type='number'
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input
                v-model="editForm.goods_number"
                type='number'
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品分类"
              prop="goods_cat"
            >
              <!-- 选择商品分类的级联选择框 -->
              <el-cascader
                :options="catelist"
                :props="cateProps"
                v-model="editForm.goods_cat"
                @change="handleChange"
                clearable
               
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品参数"
            name="1"
          >
            <!-- 渲染表单的item -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key='item.attr_id'
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key='i'
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane
            label="商品属性"
            name="2"
          >
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="商品图片"
            name="3"
          >                       
            <el-upload
              :headers='handleObj'
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
             list-type="picture"
              :file-list="uploadArr"
            >
              <el-button
                size="small"
                type="primary"
              >点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane
            label="商品内容"
            name="4"
          >
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="editForm.goods_introduce"></quill-editor>
            <!-- 修改商品的按钮 -->
            <el-button
          size="small"
              type="primary"
              class="btnedit"
              @click="edit"
            >修改商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="30%"
    >
      <img
        :src="previewPath"
        alt=""
        class="previewImg"
      >
    </el-dialog>
  </div>
</template>
<script>
// 引入lodash
const _ = require('lodash')
export default {
  props: [],
  data () {
    return {
      // 当前步骤
      currentIndex:'0',
  // 商品信息表单
  editForm:{
goods_name:'',
goods_price:0,
goods_number:0,
goods_weight:0,
// 商品所属的分类数组
goods_cat:[],
pics:[],
// 富文本内容
goods_introduce:'',
attrs:[],
 },
 // 上传图片列表
uploadArr:[]
 ,
  // 商品表单验证规则
  editRules:{
goods_name:[{required: true, message:'商品名称不能为空',trigger: 'blur'}],
goods_price:[{required: true, message:'商品重量不能为空',trigger: 'blur'}],
goods_weight:[{required: true, message:'商品重量不能为空',trigger: 'blur'}],
goods_number:[{required: true, message:'商品数量不能为空',trigger: 'blur'}],
goods_cat:[{required: true, message:'商品分类不能为空'}]
  },
    // 商品分类列表
      catelist: [],
        // 级联选择框的配置对象
      cateProps: {
        checkStrictly:true,
        expandTrigger:"hover",
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // --------------------图片上传数据---------------------
      uploadUrl:'http://127.0.0.1:8888/api/private/v1/upload',
      // 手动为上传组件请求头添加token 因为发送的请求不是axios发送的
      handleObj:{
        Authorization:window.sessionStorage.token
      },
      // 图片预览地址
      previewPath:'',
      // 预览对话框开关
      previewVisible:false,
    }
  },
  mounted () {
this.getGoodsById()
this.getCatesList()
  },
  methods: {
  // 根据id获取商品
    async getGoodsById() {
    //  获得url里面的id参数
    let urlStr = window.location.href
  let id = urlStr.substr(urlStr.indexOf('=')+1)
  // console.log(id);
      const { data: res } = await this.$http.get( `goods/${id}` )
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品失败！')
      }
      // 把获取的参数goods_cat转化成数组
      res.data.goods_cat= res.data.goods_cat.split(",")
       res.data.goods_cat=  res.data.goods_cat.map(Number)
      res.data.pics.forEach(item=>this.uploadArr.push({url:item.pics_sma_url }))
      console.log(res.data)
      // console.log(this.uploadArr)
       this.editForm=res.data
    },
    // 获取分类列表
    async getCatesList(){
      const { data: res } = await this.$http.get('categories')
      // console.log(res.data);
      if(res.meta.status !== 200){return this.$message.error('获取分类参数失败')}
     this.catelist=res.data
    },
        // 级联选择框选中项变化，会触发这个函数
    handleChange() {
      console.log(this.editForm.goods_cate);
       if (this.editForm.goods_cat.length !== 3) {
        this.editForm.goods_cat = []
      }
    },
    beforeTabLeave(activeName,oldActiveName){
      // 如果切换的tab页签是第一个并且还没有选
    if(oldActiveName==='0'&&this.editForm.goods_cat.length<3){
    this.$message.error('请先选择商品分类！')
     return false
}
    },
 async tabClicked(){
  //  console.log(this.Mock);
   //  说明访问的是参数面板
   if(this.currentIndex==='1'){
     const { data: res } = await this.$http.get(
       `categories/${this.cateId}/attributes`,{params:{ sel: 'many' }})
    console.log(res);
    if(res.meta.status !== 200){return  this.$message.error('获取动态参数列表失败')}
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      // console.log(res.data);
    this.manyTableData = res.data;
    }else if(this.currentIndex==='2'){
      const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败！')
        }

        console.log('onlyTableData', res.data)
        this.onlyTableData = res.data
    }
   },
  //  处理图片预览效果
   handlePreview(file){
  this.previewPath = file.response.data.url
      this.previewVisible = true
   },
  //  监听图片上传的删除事件
   handleRemove(file){
console.log(file);
// 获取当前删除的图片的临时路径
let filePath = file.response.data.tmp_path
// 查找当前图片在图片列表里的索引
let index = this.editForm.pics.findIndex(item=>item.pic===filePath)
// 通过索引删除图片
this.editForm.pics.splice(index,1)
 this.$message.success('删除成功')
   },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // console.log(response)
      // 1. 拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.editForm.pics.push(picInfo)
      console.log(this.editForm.pics)

    },
    // 添加商品
   async edit(){
// 先调用表单验证方法预校验
this.$refs.editFormRef.validate(async valid=>{
  if(!valid)return
  // 处理goods_cat的数据格式为字符串 不能直接操作data里的数据类型
  // 利用lodash进行深拷贝
  const form = _.cloneDeep(this.editForm)
 form.goods_cat= form.goods_cat.join(',')
// 构造请求参数attrs
// 需要把动态参数和静态参数里面的attr_id和attr_vals组成对象再拼入数组attrs
this.manyTableData.forEach(v=>
this.editForm.attrs.push({
  attr_id:v.attr_id,
  attr_value:v.attr_vals.join(' ')
})
)
this.onlyTableData.forEach(v=>
this.editForm.attrs.push({
  attr_id:v.attr_id,
  attr_value:v.attr_vals
})
)
// 把表单组装好的attrs数据复制给克隆form
form.attrs = this.editForm.attrs
// 发请求
  const { data: res } = await this.$http.put(`goods/${this.editForm.goods_id}`,
 { 
   goods_cat:form.goods_cat,
goods_name:form.goods_name,
goods_price:form.goods_price,
goods_price:form.goods_price,
goods_number:form.goods_number,
goods_weight:form.goods_weight,
goods_introduce:form.goods_introduce,
pics:form.pics,
attrs:form.attrs

 }
 
 )
  console.log(res);
  if(res.meta.status !== 200){return this.$message.error('修改商品失败')}
  this.$message.success('修改商品成功')
  // 跳转到商品列表页面
  this.$router.push('/goods')
})
    }
   
   },
   computed:{
    // 返回请求数组里面最后一项的id
    cateId(){
      if(this.editForm.goods_cat .length===3){
      return  this.editForm.goods_cat [2]
    }
    return null 
  }
  }
}
</script>
<style lang="less" scoped>
.el-cascader{
  width: 100%;
}
.el-steps{
  width: 100%;
  margin-top: 15px;
}
::v-deep .el-step__title {
  font-size: 14px;
}
.previewImg{
  width: 100%;
}
.btnedit{
  margin-top: 15px;
}
</style>